package com.xinpu.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SignatureJSSDKUtil
 *
 * @author ayuan
 * @date 2021/5/27
 */
public class SignatureJSSDKUtil {

    /**
     * 制作签名
     *
     * @param noncestr
     * @param jsapi_ticket
     * @param timestamp
     * @return
     */
    public static String genSignatureJSSDK(String noncestr, String jsapi_ticket, Long timestamp, String url) {
        StringBuffer sb = new StringBuffer();
        sb.append("jsapi_ticket=" + jsapi_ticket)
                .append("&noncestr=" + noncestr)
                .append("&timestamp=" + timestamp)
                .append("&url=" + url);
        return sha1(sb.toString().trim());
    }


    /**
     * sha1签名算法
     *
     * @param decript
     * @return
     */
    private static String sha1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
